import React, { Component } from 'react';
import baseService from 'share/base.service';
import paymentService from '../payment-service';
import expenseReportService from '../../expense-report/expense-report.service';
import PaymentHeader from 'containers/payment-request/component/header';
import PaymentField from 'containers/payment-request/component/field';
import PaymentPayInfo from 'containers/payment-request/component/payment-pay-info';
import 'styles/payment-request/payment-content.scss';
import expenseReportFunction from '../../expense-report/expense-report.function';
import AffixButton from './affix-botton';
import { getQueryUrlParam, messages } from 'share/common';
import { Affix, message, Modal } from 'antd';
import Condition from 'components/condition';
import ApproveBar from 'components/template/approve-bar';
import ApproveExpenseReportService from 'containers/approve/expense-report/approve-expense-report.service';
import adminApproveListService from '../../setting/process-monitoring-platform/admin-approve-list.service';
import loadingImg from 'images/expense-report/loading.png';
import auditingImg from 'images/expense-report/auditing.png';
import approveService from '../../approve/approve.service';
import { connect } from "react-redux";
import menuRoute from 'routes/menuRoute';

const { getReportStatus } = expenseReportFunction;
const { If, Else } = Condition;

class PaymentContent extends Component {
  allButtons = {
    submit: {
      child: messages('common.submit')/*提交*/,// 提交
      params: {
        type: 'primary',
        onClick: () => this.handleSubmit(),
        key: 'submit'
      }
    },
    delete: {
      child: messages('expense-18.key36')/*删除单据*/,
      params: {
        type: 'danger',
        onClick: () => this.handleDelete(),
        key: 'delete'
      }
    },
    back: {
      child: messages('common.back')/*返回*/,
      params: {
        type: 'default',
        onClick: () => this.handleGoBack(),
        key: 'back'
      },
      withdraw: {
        child: messages('expense-18.key37')/*撤回单据*/,
        params: {
          type: 'default',
          onClick: () => this.handleWithdraw(),
          key: 'withdraw'
        }
      }
    }
  };

  state = {
    loading: false,
    applicant: {},
    jobInfo: {},
    paymentDetails: {},
    readOnly: false,
    formDetail: {},
    buttons: ['back'],
    showChecking: false,
    showAdditionalBtn: false,
    signCompanyOIDs:[],
    showHangUp: false
  };


  componentDidMount() {
    this.init();
  }

  init = () => {
    this.setState({ loading: true });
    Promise.all([this.getInfo(), this.getForm()])
      .finally(() => {
        this.setState({ loading: false });
      });
  };

  getApplicantInfo = async () => {
    const { paymentDetails: { applicantOID } } = this.state;
    paymentService.applicant = {};
    const ret = await baseService.getUserByOID(applicantOID);
    paymentService.applicant = ret.data;
    this.setState({ applicant: ret.data });
  };

  getJobInfo = async () => {
    const { paymentDetails: { applicantJobId } } = this.state;
    const ret = await expenseReportService.getJobInfo(applicantJobId);
    this.setState({ jobInfo: ret.data });
  };

  getInfo = async (refreshInfo) => {
    const { paymentRequestOID } = this.props;
    let { buttons } = this.state;
    paymentService.paymentDetails = {};
    try {
      const ret = await paymentService.getPaymentRequest(paymentRequestOID);
      const reportStatus = getReportStatus(ret.data);
      this.showAdditional(ret.data.formOID);
      const readOnly = reportStatus.operate !== 'edit' || getQueryUrlParam('readOnly');
      if (!readOnly) {
        buttons = ['submit', 'delete', 'back' ];
      }
      await this.setState({ paymentDetails: ret.data, readOnly, buttons });
      paymentService.paymentDetails = ret.data;
    }
    catch (e) {
      setTimeout(() => {
        this.handleGoBack(false);
      }, 2000);
    }
    !refreshInfo && await Promise.all([this.getApplicantInfo(), this.getJobInfo()]);

  };

  handleRefresh = async () => {
    await this.setState({ loading: true });
    await this.getInfo(true);
    await this.setState({ loading: false, isRefreshList: true });
  };

  getForm = async () => {
    const { paymentRequestOID } = this.props;
    const ret = await paymentService.getFormDetail(paymentRequestOID);
    await this.setState({ formDetail: ret.data.rows });
  };

  handleDelete = async () => {
    const { paymentRequestOID } = this.props;
    Modal.confirm({
      title: messages('expense-18.key36')/*删除单据*/,
      content: messages('expense-18.key38')/*确定删除该单据？*/,
      onOk: async () => {
        await this.setState({ buttonLoading: true });
        try {
          await paymentService.deletePayment(paymentRequestOID);
          message.success(messages('common.delete.successful')/*删除成功*/);
          this.handleGoBack(true);
        }
        catch (e) {
        }
        await this.setState({ buttonLoading: false });
      }
    });
  };

  handleGoBack = (flag) => {
    if (location.pathname.indexOf('approve-payment-detail') > -1){
      // TODO 只改了废弃的key，可能还需修改返回逻辑
      if (location.search.indexOf('approvePending') > -1 ) {
        const backURL = menuRoute.getRouteItem('to-be-approve').url
        this.context.router.push(backURL);
        return;
      } else {
        const backURL = menuRoute.getRouteItem('done-approved').url
        this.context.router.push(backURL);
        return;
      }
    }
    if (location.pathname.indexOf('entry-information') > -1) {
      this.context.router.push(menuRoute.getRouteItem('entry-information').url);
    }
    const { close } = this.props;
    const { isRefreshList, readOnly } = this.state;
    close ? close(!!flag || isRefreshList) : window.history.go(readOnly ? -1 : -2);
  };

  handleSubmit = async () => {
    const { paymentRequestOID } = this.props;
    await this.setState({ buttonLoading: true, showChecking: true, checkingText: messages('common.submitting')/*正在提交...*/ });
    try {
      await paymentService.submitPaymentRequest(paymentRequestOID);
      message.success(messages('expense-18.key39')/*提交成功*/);
      this.handleGoBack(true);
    }
    catch (e) {
    }
    await this.setState({ buttonLoading: false, showChecking: false });
  };


  hasRepeatApproveTip = async (values) => {
    this.setState({ passLoading: true });
    const { reason, honestEvent, additionalItems } = values;
    const { approvalHistoryDTOs } = this.props;
    let additionalOIDs = [];
    let additionalHaveApprovedNames = [];  //加签人中已审批的用户名
    additionalItems.map(item => {
      additionalOIDs.push(item.userOID);
    });
    let ids = [];
    honestEvent.map(item => {
      ids.push(item.id);
    });
    let preApproveOIDs = [];
    approvalHistoryDTOs.map(item => {
      item.operation === 2001 && (preApproveOIDs.push(item.operatorOID));
    });
    additionalOIDs.map((OID, index) => {
      if (preApproveOIDs.indexOf(OID) > -1) {
        additionalHaveApprovedNames.push(additionalItems[index].fullName);
      }
    });
    if (additionalHaveApprovedNames.length) {
      Modal.confirm({
        title: `${additionalHaveApprovedNames.join('、')} ${messages('expense-18.key40')/*已经审批通过，是否继续*/}？`,
        onOk:async () => await this.handleApprovePass(reason, additionalOIDs, ids)
      });
    } else {
     await this.handleApprovePass(reason, additionalOIDs, ids);
    }
  };

  //审批通过
  handleApprovePass = async (value, additionalOIDs, ids) => {
    const { paymentRequestOID, approverOID, admin } = this.props;
    const params = {
      approvalTxt: value,
      entities: [{
        approverOID: approverOID,
        entityOID: paymentRequestOID,
        entityType: 7001,
        countersignApproverOIDs: additionalOIDs
      }],
      conditionIds: ids
    };
    await this.setState({ passLoading: true });
    const handleService = admin ? adminApproveListService.handleRequestApprovePass : ApproveExpenseReportService.handleExpenseReportApprovePass;
    try {
      const res = await handleService(params);
      if (res.data.failNum === 0) {
        message.success(messages('common.operate.success')/*操作成功*/);
        this.handleGoBack(true);
      } else {
        message.error(messages('common.operate.filed')/*操作失败*/);
      }
    }
    catch (e) {
      message.error(`${messages('common.operate.filed')/*操作失败*/}，${e.response.data.message}`);
    }
    this.setState({ passLoading: false });
  };

  // 审批驳回
  handleApproveReject = async ({ reason, honestEvent, additionalItems }) => {
    const { paymentRequestOID, approverOID, admin } = this.props;

    let additionalOIDs = [];
    additionalItems.map(item => {
      additionalOIDs.push(item.userOID);
    });
    let ids = [];
    honestEvent.map(item => {
      ids.push(item.id);
    });
    const params = {
      approvalTxt: reason,
      entities: [{
        approverOID: approverOID,
        entityOID: paymentRequestOID,
        entityType: 7001,
      }],
      conditionIds: ids
    };
    await this.setState({ rejectLoading: true });
    additionalOIDs && (params.entities[0].countersignApproverOIDs = additionalOIDs);
    const handleService = admin ? adminApproveListService.handleRequestApproveReject : ApproveExpenseReportService.handleExpenseReportApproveReject;
    try {
      const res = await handleService(params);
      if (res.status === 200) {
        const { failNum } = res.data;
        if (failNum !== 0) {
          message.error(messages('common.operate.filed')/*操作失败*/);
        } else {
          this.handleGoBack(true);
          message.success(messages('common.operate.success')/*操作成功*/);
        }
      }
    }
    catch (e) {
      message.error(`${messages('common.operate.filed')/*操作失败*/}，${e.response.data.message}`);
    }
    this.setState({ rejectLoading: false });
  };


  //撤回
  handleWithdraw = async () => {
    const { info, approvalChains } = this.props;
    Modal.confirm({
      title: messages('expense-18.key37')/*撤回单据*/,
      content: messages('expense-18.key41')/*确定撤回该单据？*/,
      onOk: async () => {
        await this.setState({ withdrawing: true });
        let params = {
          entities: [{
            entityOID: approvalChains[0] && approvalChains[0].entityOID,
            entityType: approvalChains[0] && approvalChains[0].entityType
          }]
        };
        try {
          const res = await expenseReportService.withdraw(params);
          if (res.data.failNum > 0) {
            if (res.data.failReason[info.expenseReportOID]) {
              message.error(`${messages('common.operate.filed')/*操作失败*/}，${res.data.failReason[info.expenseReportOID]}`);
            } else {
              message.error(messages('common.operate.filed')/*操作失败*/);
            }
          } else {
            message.success(messages('expense-18.key42')/*已撤回*/);
            this.handleGoBack(true);
          }
        }
        catch (e) {
          message.error(`${messages('common.operate.filed')/*操作失败*/}，${e.response.data.message}`);
        }
        this.setState({ withdrawing: false });
      }
    });
  };

  //是否展示挂起
  isShowHangUp = () => {
    const { approvalChains, approverOID } = this.props;
    let showHangUp = false;
    approvalChains && approvalChains.map(chain => {
      if (chain.approverOID === approverOID && chain.pending) {
        showHangUp = true;
      }
    });
    return showHangUp;
  };

  //判断是否可以加签
  showAdditional = (formOID) => {
    const { company,  approverOID , paymentRequestOID} = this.props;
    let params = {
      companyOID: company.companyOID,
      formOID: formOID,
      counterSignType: 'enableAddSign',
      approverOID: approverOID,
      entityOID: paymentRequestOID,
      entityType: 7001 //付款申请单
    };
    approverOID && formOID && (
      approveService.postAddSignEnableScope(params).then(res =>{
        if (res.data.enabled) {
          //加签人范围
          this.setState({ showAdditionalBtn: res.data.enabled, signCompanyOIDs: res.data.approvalAddSignScope.companyOIDs });
        }
      })
    )
  };

  //暂挂单据
  handleApproveHangUp = () => {
    const { approverOID, paymentRequestOID } = this.props;
    let params = {
      entities: [{
        approverOID: approverOID,
        entityOID: paymentRequestOID,
        entityType: 7001 //申请单
      }]
    };
    this.setState({ allLoading: true });
    approveService.handleEntityHangUp(params)
      .then(res => {
        if (res.data.failNum === 0) {
          message.success(messages('common.operate.success')/*操作成功*/);
          this.handleGoBack(true);
        } else {
          message.error(`${messages('common.operate.filed')/*操作失败*/}，${res.data.failReason[this.state.info.applicationOID]}`);
        }
      })
      .catch(e => {
        message.error(`${messages('common.operate.filed')/*操作失败*/}，${e.response.data.message}`);
      })
      .finally(() => {
        this.setState({ allLoading: false });
      });
  };


  render() {
    const { paymentDetails, jobInfo, applicant, loading, readOnly, buttons, buttonLoading, formDetail: { customFormPropertyMap= {}  }, passLoading, allLoading, rejectLoading, showChecking, checkingText, formDetail, showAdditionalBtn, signCompanyOIDs } = this.state;
    const { entry, paymentRequestOID, approverOID, approvalChains, admin, isShowApproval, } = this.props;
    const buttonsCopy = buttons.map(item => this.allButtons[item]);
    let moreButtons = [];
    const approvalButtons = ['pass', 'reject', 'skip', 'press'];
    !this.isShowHangUp() && moreButtons.push('hangUp'); //已挂起单据不展示暂挂
    showAdditionalBtn && moreButtons.push('additional');
    customFormPropertyMap['approvalIsDeliver'] === 'true' && moreButtons.push('approveTransfer');
    const expenseReportStatus = getReportStatus(paymentDetails);
    if (
      !getQueryUrlParam('readOnly') &&
      !approverOID &&
      expenseReportStatus.operate === 'processing' &&
      approvalChains[0] &&
      approvalChains[0].entityOID &&
      customFormPropertyMap &&
      ['1','2'].includes(customFormPropertyMap.formWithdrawAuthority)
    ) {
      buttonsCopy.unshift({
        child: messages('expense-18.key37')/*撤回单据*/,
        params: {
          type: 'default',
          onClick: () => this.handleWithdraw(),
          key: 'withdraw'
        }
      });
    }
    if(admin) {
      moreButtons = [];
    }
    return (
      <section className="payment-content">
        <PaymentHeader
          loading={loading}
          info={paymentDetails}
          entry={entry}
          jobInfo={jobInfo}
          applicant={applicant}
          readOnly={readOnly}
        />
        <Line/>
        <PaymentField
          info={paymentDetails}
          refresh={this.handleRefresh}
          jobInfo={jobInfo}
          loading={loading}
          applicant={applicant}
          readOnly={readOnly}
        />
        <Line/>

        <PaymentPayInfo
          formOID={paymentDetails.formOID}
          paymentRequestOID={paymentRequestOID}
          applicantOID={paymentDetails.applicantOID}
          readOnly={readOnly}
          refresh={this.handleRefresh}
        />
        <Condition>
          <If value={(isShowApproval || admin) && !!approverOID}>
            <Affix offsetBottom={0} className="bottom-bar bottom-bar-approve payment-content-bottom">
              <ApproveBar
                admin={admin}
                buttons={approvalButtons}
                passLoading={passLoading}
                allLoading={allLoading}
                moreButtons={moreButtons}
                style={{ paddingLeft: 20 }}
                rejectLoading={rejectLoading}
                signCompanyOIDs={signCompanyOIDs}
                goBack={this.handleGoBack}
                handleApproveTransfer={this.handleGoBack}
                handleApproveAdditional={this.handleGoBack}
                handleApprovePass={this.hasRepeatApproveTip}
                handleApproveReject={this.handleApproveReject}
                handleApproveHangUp={this.handleApproveHangUp}
                handleApproveSkip={() => this.handleGoBack(false)}
                entities={{
                  approverOID: approverOID || getQueryUrlParam('approverOID'),
                  entityOID: paymentRequestOID,
                  entityType: 7001
                }}
              />
            </Affix>
          </If>
          <Else>
            <AffixButton
              info={paymentDetails}
              form={formDetail}
              loading={buttonLoading}
              className="payment-details-buttons"
              buttons={buttonsCopy}
              refreshHistory={this.props.refreshHistory}
            />
          </Else>
        </Condition>

        <Modal
          visible={showChecking}
          maskClosable={false}
          footer={null}
          closable={false}
          wrapClassName="expense-report-checking"
        >
          <img src={loadingImg} className="checking-img"/>
          <img src={auditingImg} className="checking-img-content"/>
          <div className="checking-divide"/>
          <div className="checking-title">{checkingText}</div>
          <div className="checking-content">{messages('common.waiting')/*请稍等...*/}</div>
        </Modal>
      </section>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
  };
}

PaymentContent.propTypes = {};


PaymentContent.contextTypes = {
  router: React.PropTypes.object
};

export default connect(mapStateToProps)(PaymentContent);

function Line() {
  return <section className="payment-content-line"/>;
}
